package com.huak.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.RetryNTimes;

/**
 * @author liuhuan
 * @date 2018/9/24 09:08
 * @description
 */
public class CuratorOperator {
    public CuratorFramework client=null;
    public static final String SERVER_PATH="192.168.0.128:2181";

    public CuratorOperator(){
        /**
         * curator连接zk的策略:ExponentialBackoffRetry
         * baseSleepTimeMs:初始sleep时间
         * maxRetries:最大重试次数
         * maxSleepMs：最大重试时间
         */
       // RetryPolicy retryPolicy =new ExponentialBackoffRetry(1000,5);
        /**
         * curator连接zk的策略:RetryNTimes
         * n:重试次数
         * sleepMsBetweenRetries:每次重试间隔时间
         */
        RetryPolicy retryPolicy=new RetryNTimes(3,5000);

        client= CuratorFrameworkFactory.builder().connectString(SERVER_PATH).sessionTimeoutMs(10000).retryPolicy(retryPolicy).namespace("workspace").build();
        client.start();
    }

    public void closeClient(){
        if(client!=null){
            client.close();
        }
    }

    public static void main(String[] args) throws Exception{
        //实例化
        CuratorOperator curatorOperator=new CuratorOperator();

        boolean isZkclientStarted=curatorOperator.client.isStarted();

        System.out.println("当前客户端的状态："+(isZkclientStarted ?"连接中":"已关闭"));

        //创建节点
        String node="/super/imooc";
//        byte [] data="superme".getBytes();
//        curatorOperator.client.create().creatingParentsIfNeeded()
//                .withMode(CreateMode.PERSISTENT).withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
//                .forPath(node,data);

        //修改节点
//        byte [] newData="newData".getBytes();
//        curatorOperator.client.setData().withVersion(0).forPath(node,newData);

        //删除节点
//        curatorOperator.client.delete()
//                .guaranteed() //如何删除失败，在后端还是继续会删除，直到成功
//                .deletingChildrenIfNeeded() //如果有子节点就删除
//                .withVersion(1)
//                .forPath(node);
        //查询节点
//        Stat stat=new Stat();
//        byte []data=curatorOperator.client.getData().storingStatIn(stat).forPath(node);
//        System.out.println("节点"+node+"的数据为:"+new String(data));
//        System.out.println("该节点的版本号为" + stat.getVersion());

        //watch事件 当使用UsingWatcher的时候，监听只会触发一次，监听完毕后就销毁
        //curatorOperator.client.getData().usingWatcher(new MyCuratorWatcher()).forPath(node);
        //curatorOperator.client.getData().usingWatcher(new MyWatcher()).forPath(node);

        //nodeCache:监听数据节点的变更，会触发事件
        final NodeCache nodeCache=new NodeCache(curatorOperator.client,node);

        //buildInitial :初始化获取node的值并缓存
        nodeCache.start(true);

        if(nodeCache.getCurrentData()!=null){
            System.out.println("节点的初始化数据为" + new String(nodeCache.getCurrentData().getData()));
        }else{
            System.out.println("节点的数据为空");
        }

        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                String data=new String(nodeCache.getCurrentData().getData());
                System.out.println("节点路径" + nodeCache.getCurrentData().getPath() + ",数据：" + data);
            }
        });




        Thread.sleep(100000);

        curatorOperator.closeClient();
        boolean isZkclientStarted2=curatorOperator.client.isStarted();

        System.out.println("当前客户端的状态："+(isZkclientStarted2 ?"连接中":"已关闭"));
    }

}
